//节点类
class Node{
    constructor(element){
        this.element = element;
        this.next = null;
    }
}

//创建单向链表类
class LinkedList{
    constructor(){
        this.head = null;   //链表头
        this.count = 0;     //记录节点数量
    }

    //在链表的末尾添加
    push(element){
        let node = new Node(element);
        if(this.head === null){
            //链表为空
            this.head = node;
        }else{
            let current = this.head;
            while(current.next != null){
                current = current.next;
            }
            current.next = node;
        }
        this.count++;
    }

    getElementAt(index){
        let current = this.head;
        for(let i = 0;i < index;i++){
            current = current.next;
        }
        return current
    }

    //删除
    removeAt(index){
        if(index >= 0 && index <= this.count){
            //1.链表开头删除
            let current = this.head;
            if(index === 0){
                this.head = current.next;
            }else{
                let prev = this.getElementAt(index - 1);
                current = prev.next;
                prev.next = current.next;
            }
            this.count--;
            return current.element
        }else{
            return undefined
        }
    }

    //插入
    insert(element,index){
        if(index >= 0 && index <= this.count){
            let node = new Node(element);
            //1.是否是在开头插入
            if(index === 0){
                if(this.head === null){
                    this.head = node;
                }else{
                    let current = this.head;
                    this.head = node;
                    node.next = current;
                }
            }else{
                let prev = this.getElementAt(index - 1);
                let current = prev.next;
                prev.next = node;
                node.next = current;
            }

            this.count++;
        }else{
            return false
        }
    }
}

let l = new LinkedList();

l.push('a');

l.push('b');

// console.log(l.removeAt(1));

l.insert('c',2);

console.log(l);

